﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ypn.common.csharp
{
    /// <summary>
    /// 日志工具类
    /// </summary>
    public class LogHelper
    {
        /// <summary>
        /// 将异常写入Log file
        /// </summary>
        /// <param name="i_ex">异常</param>
        /// <param name="i_logFile">日志文件名（默认ApplicationException）</param>
        public static void WriteLog(Exception i_ex, string i_logFile = "ApplicationException")
        {
            try
            {
                string v_logDir = Environment.CurrentDirectory + @"\log";
                if (!Directory.Exists(v_logDir))
                {
                    Directory.CreateDirectory(v_logDir);
                }
                string v_logFilePath = v_logDir + @"\" + i_logFile + @".log";
                StreamWriter fs = new StreamWriter(v_logFilePath, true);
                fs.WriteLine("[" + Environment.OSVersion + "] " +
                             "[" + Environment.Version + "] " +
                             "[" + i_ex.TargetSite.Module.Assembly + "] " +
                             DateTimeHelper.FormatDateTime(DateTime.Now, "1") + ":");
                fs.WriteLine(i_ex);
                fs.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("将异常写入Log file失败：" + ex);
            }
        }
    }
}
